import {
  Catch,
  HttpException,
  ExceptionFilter,
  ArgumentsHost
} from '@nestjs/common';
import { Request, Response } from 'express';

// 捕获HttpException异常
@Catch(HttpException)
export class JcExceptionFilter implements ExceptionFilter {
  // 捕获异常的方法
  catch(exception: HttpException, host: ArgumentsHost) {
    // 获取http上下文
    const ctx = host.switchToHttp();
    // 获取响应对象
    const response = ctx.getResponse<Response>();
    // 获取请求对象
    const request = ctx.getRequest<Request>();
    // 获取异常状态码
    const status = exception.getStatus();
    // 获取异常信息
    const msg = () => {
      const res = exception.getResponse();
      if (typeof res == 'object') {
        const { message } = res as { message: string };
        return message;
      }
      return res;
    };
    // console.log(exception);
    // 设置响应状态码和响应体
    response.status(status).json({
      success: false,
      statusCode: status,
      timestamp: new Date().toLocaleString(),
      path: request.url,
      message: msg()
    });
  }
}
